function showErrorMsg(msg){
	Ext.example.msg('', msg, '');
}

// 获取段子菜单
var getAllArticleMenuStore = Ext.create('Ext.data.Store', {
     model: 'app.model.MenuModel',
     proxy: {
         type: 'ajax',
         url: 'getAllArticleMenu',
         reader: {
             type: 'json',
             root: 'data'
         }
     },
     autoLoad: false
 });

var tbar = Ext.create('Ext.toolbar.Toolbar', {
	dock : 'top',
	layout: {  
        overflowHandler: 'Menu'  
    },  
	items : [{
		id:'menuId',
		xtype : 'combo',
		fieldLabel : '分类',
		labelWidth : 30,
		store : getAllArticleMenuStore,
		displayField : 'menuName',
		valueField : 'id',
		name : 'menuId',
		typeAhead:false,
		editable:false,
		triggerAction : 'all',
		emptyText : '===请选择===',
		anchor : '95%',
		width : 170
	},{
		id:'type',
		xtype : 'combo',
		fieldLabel : '是否有图',
		labelWidth : 60,
		store : [	['0', '全部'],
					['1', '无图'],
	                ['2', '有图']],
		name : 'type',
		valueField : 'id',
		typeAhead:false,
		editable:false,
		value:'0',
		triggerAction : 'all',
		emptyText : '==请选择==',
		anchor : '95%',
		width : 150
	},{
		id:'content',
		xtype : 'textfield',
		name : 'content',
		fieldLabel : '内容关键字',
		labelWidth : 70,
		width : 360,
		emptyText : '===========请填写关键字==========='
			
	},{
		id:'createTime',
		xtype : 'datefield',
		name : 'createTime',
		format : "Y-m-d",
		fieldLabel : '创建时间',
		//value:Ext.util.Format.date(Ext.Date.add(new Date(),Ext.Date.DAY,-7),"Y-m-d"),
		labelWidth : 60,
		width : 205,
		emptyText : '',
	}, {
		text : '查询',
		handler : function() {
			search();
		}
	},{
		text : '重置',
		handler : function() {
			Ext.getCmp("menuId").setValue("");
			Ext.getCmp("type").setValue("0");
			Ext.getCmp("content").setValue("");
			Ext.getCmp("createTime").setValue("");
			search();
		}
	},{
		text : '添加',
		handler : function() {
			addArticle();
		}
	}]
});


//时间格式化 YYYY-MM-DD
var dateTimeFormat = function(time, format){
    var t = new Date(time);
    var tf = function(i){return (i < 10 ? '0' : '') + i};
    return format.replace(/yyyy|MM|dd/g, function(a){
        switch(a){
            case 'yyyy':
                return tf(t.getFullYear());
                break;
            case 'MM':
                return tf(t.getMonth() + 1);
                break;
            case 'dd':
                return tf(t.getDate());
                break;
        }
    })
}

function search(){
	var content = encodeURIComponent(Ext.getCmp("content").getValue());
	var menuId = Ext.getCmp("menuId").getValue();
	var type = Ext.getCmp("type").getValue();
	var createTime = Ext.getCmp("createTime").getValue()==null ? '' : dateTimeFormat(Ext.getCmp("createTime").getValue(), 'yyyy-MM-dd');
	
	// 获取grid的store
	var articleStore = Ext.getCmp("articleGrid").getStore();
	articleStore.load({
		params : {
			content : content,
			menuId:menuId,
			type:type,
			createTime:createTime,
			page : 1,
			start : 0,
			limit : 20
        }
	});
	articleGrid.currentPage=1
}

Ext.define("app.view.ArticleGrid", {
			extend : "Ext.grid.Panel",
			xtype: 'cell-editing',
			alias : "widget.articleGrid",
			id : "articleGrid",
			width:700,
			height:350,
			viewConfig:{
		         loadMask:false  // grid去掉加载中的提示
		    },
			selModel : {
				//selType : "checkboxmodel"
			},
			border : 0,
			multiSelect : true,
			frame : false, // 不要边框
			tbar : tbar,
			bbar : {
				xtype : 'pagingtoolbar',
				store : 'ArticleStore',
				dock : 'bottom',
				displayInfo : true
			},
			viewConfig:{  
		        enableTextSelection:true  // 文本可选择
		    },
			enableKeyNav : true,
			columnLines : true,
			forceFit :true, // 宽度自适配
			columns : [{
						text:"序号",
						dataIndex:"id",
						width:26
					},{
						text : "段子内容",
						dataIndex : "content",
						width : 170,
		                editor: {
		                	xtype : "textfield",
		                    allowBlank: false
		                }
					},{
						text : "是否有图",
						dataIndex : "type",
						width : 36,
						editor : {
			                xtype : 'combobox',
			                editable : false,
			                store : [['1', '无图'],
	                         ['2', '有图']]
						},
						renderer : function(v, p, record, rowIndex, colIndex) { // 值自定义渲染
					        if(v == '1'){
					        	return "无图";
					        }else if(v == '2'){
					        	return "有图";
					        }
					    }
					},{
						text : "分类",
						dataIndex : "menuName",
						width : 35,
						editor : {
							xtype : "textfield",
		                    allowBlank: false
			            }
					},{
						text : "创建时间",
						dataIndex : "createTime",
						width : 35,
						editor : {
							xtype : "textfield",
							format:'Y-m-d'
						}
					},{
		                xtype: 'actioncolumn',
		                width: 35,
		                tdCls: 'action',  
		                text: '操作',  
		                sortable: false,
		                menuDisabled: true,
		                items: [{
		                	icon: 'js/ext-4.2/resources/ext-theme-neptune/images/icon/add.png',
		                    tooltip: '查看',
		                    scope: this,
		                    handler: function(grid, rowIndex, colIndex) {
		                    	var record = grid.getStore().getAt(rowIndex);
		                        var id = record.get('id');
		                        this.loadArticleById(grid,id);
		                    },
		                    getClass: function(v, meta, record) {
		                    	return '';
		                    }
		                }
		                ]
		            }],
			listeners: { 
				itemdblclick:function(grid,row){
		            var id = row.data.id;
		            loadArticleById(grid,id);
		        }
			},					
			initComponent : function() {
				// 可编辑插件
				this.callParent(arguments);
			},
			store : "ArticleStore"
});

// 查看段子明细
function loadArticleById(grid,id){
	var store = grid.getStore();
	var win = Ext.create('Ext.window.Window', {
    	autoShow: false,
        title: '段子详情',
        width: 484,
        height: 483,
        minWidth: 300,
        minHeight: 200,
        layout: 'fit',
        plain:true,
        modal: 'true',  // 模态
        collapsible: true, //允许缩放条  
        closeAction: 'destroy',  
        autoScroll: true,
        maximizable :true,
        loader: {
            url:'getArticleInfoById?id='+id,
            scripts: true,
            autoLoad: true
        },
        listeners:{
        	'beforerender':function(){
        		//myMask.show();  
        	}
       },
        buttonAlign: "center",  
        buttons: [{
            text: '上一个',
            handler: function() {
            	// 获取上一个
            	var newId = getId(1,id);
            	if(newId == null || newId == ''){
            		Ext.example.msg('', '无数据', '');
            	}else{
	            	win.getLoader().load({  
	                    url : './getArticleInfoById?id='+newId
	                });
	                id = newId;
            	}
            }
        },{
            text: '删除',
            handler: function() {
            	$.ajax({
        			url : './delArticle?id='+id,
        			type : "post",
        			dataType : "json",
        			async: true,
        			success : function(data) {
        				if (data.resultCode == 'error') {
        					Ext.example.msg('','操作失败', '');
        					return;
        				} else if (data.resultCode == 'success') {
        					// 弹出新增成功消息框 
        					Ext.example.msg('', '操作成功', '');
        					search();
        					// 关闭窗口
        					win.close();
        				}
        			}
        		});
            }
        },{
            text: '下一个',
            handler: function() {
            	// 获取下一个
            	var newId = getId(2,id);
            	if(newId == null || newId == '' || newId == 'null'){
            		Ext.example.msg('', '无数据', '');
            	}else{
	            	win.getLoader().load({  
	                    url : './getArticleInfoById?id='+newId
	                });
	                id = newId;
            	}
            }
        }]
    });
    
    win.show();
}

function getId(orient,value){
	var id = 0;
	var content = encodeURIComponent(Ext.getCmp("content").getValue());
	var menuId = Ext.getCmp("menuId").getValue();
	var type = Ext.getCmp("type").getValue();
	
	Ext.Ajax.request({
			url : "getArticleId",
			params : {
				id:value,
				content:content,
				menuId:menuId,
				type:type,
				orient:orient,
			},
			type : "POST",
			timeout : 4000,
			async:false,
			success : function(response, opts) {
				var obj = eval('('+response.responseText+')');
				id = obj.data;
			}
	});
	
	return id;
}

//添加段子
function addArticle(){
    var win = Ext.create('Ext.window.Window', {
    	autoShow: false,
        title: '添加段子',
        width: 484,
        height: 370,
        minWidth: 300,
        minHeight: 200,
        layout: 'fit',
        plain:true,
        modal: false,  // 模态
        collapsible: true, //允许缩放条  
        closeAction: 'destroy', 
        autoScroll: true,
        maximizable :true,
        loader: {
            url:'addArticle?data='+Math.random(),
            scripts: true,
            autoLoad: true
        },
        listeners:{
//        	'beforerender':function(){
//        		myMask.show();  
//        	}
        },
        buttonAlign: "center",  
        buttons: [{
            text: '保存',
            handler: function() {
            	// 校验
            	if(validateSave()){
                	var dataParm = decodeURIComponent($("#add_info_form").serialize(),true);
                	dataParm = encodeURI(encodeURI(dataParm));
                	$.ajax({
            			url : './saveArticle?data='+Math.random(),
            			data: dataParm,
            			type : "post",
            			dataType : "json",
            			async: true,
            			success : function(data) {
            				if (data.resultCode == 'error') {
            					Ext.example.msg('','保存段子出错!', '');
            					return;
            				} else if (data.resultCode == 'success') {
            					// 弹出新增成功消息框 
            					Ext.example.msg('', '操作成功', '');
            					search();
            					// 关闭窗口
            					win.close();
            				}
            			}
            		});
            	}
            }
        },{
            text: '取消',
            handler: function() {
            	// 关闭窗口
            	win.close();
            }
        }]
    });
    win.show();
}
